//
//  FPSettleDetailController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/19.
//

#import "FPSettleDetailController.h"
#import "FPLoanDetailModel.h"
#import <Photos/Photos.h>
#import "FPSettleModel.h"
#import "FPSettleDetailCell.h"

@interface FPSettleDetailController () <UITableViewDelegate , UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *bottomToSafeAreaView;
@property (nonatomic , strong) FPSettleModel *model;
@property (nonatomic , assign) CGFloat rowHeight;

@end

@implementation FPSettleDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {

    self.saveBtn.hidden = YES;
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    self.bottomView.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    self.bottomToSafeAreaView.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    [self setTitle:@"开具证明" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.saveBtn.clipsToBounds = YES;
    self.saveBtn.layer.cornerRadius = 22.f;
    self.saveBtn.backgroundColor = MAIN_BLUE_COLOR;
    
    [MBManager showLoadingEnable:YES];
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - 70.f - UIDevice.safeDistanceBottom - UIDevice.navigationFullHeight);
    self.tableView.backgroundColor = UIColor.clearColor;
    
    [self performSelector:@selector(getData) withObject:nil afterDelay:1.5f];
    
    [self.view bringSubviewToFront:self.tableView];
}



- (void)getData {
    
//    [MBManager showLoading];
    [FPSettleModel getSettleDetailWithID:self.loanID success:^(NSInteger code, NSString * _Nonnull message, FPSettleModel * _Nonnull model) {
        [MBManager hideLoading];
        
        [self.dataSource removeAllObjects];
        if (code == 200) {
            
            self.model = model;
            [self.dataSource addObject:@"source one"];
            [self refreshUIWithModel:model];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (void)refreshUIWithModel:(FPSettleModel *)model {
    
    self.model = model;
    
    [self.tableView reloadData];
    
    self.saveBtn.hidden = NO;
    
    NSString *finalStr = [FPSettleDetailCell getFinalString:model];
    
    CGFloat height = 450.f - 15.f - 50.f + [UIView heightWithString:finalStr labelWidth:SCREEN_WIDTH - 32.f - 48.f fontSize:12.f];
    self.rowHeight = height;
    self.tableView.rowHeight = height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *finalStr = [FPSettleDetailCell getFinalString:self.model];
    
    CGFloat height = 450.f - 15.f - 80.f + [UIView heightWithString:finalStr labelWidth:SCREEN_WIDTH - 32.f - 48.f fontSize:12.f];
    
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPSettleDetailCell *cell;
    
    if (!cell) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPSettleDetailCell.class) owner:nil options:nil].lastObject;
    }
    
    [cell refreshUIWithModel:self.model];
    
    return cell;
}






- (IBAction)saveAction:(UIButton *)sender {
    
    [self.tableView layoutIfNeeded];
    
//    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:self.tableView.contentSize];
//        
//    // 使用渲染器绘制截图
//    UIImage *screenshot = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull context) {
//        [self.tableView.layer renderInContext:context.CGContext];
//    }];
    
    // 获取整个 tableView 的 contentSize（包括不可见部分）
    CGSize contentSize = self.tableView.contentSize;
    
    // 输出 contentSize 确保它正确
    NSLog(@"contentSize: %@", NSStringFromCGSize(contentSize));
    
    // 创建图形上下文，大小为整个 contentSize 的大小
    UIGraphicsBeginImageContextWithOptions(contentSize, NO, 0.0);
    
    // 保存当前的 contentOffset（防止截图时改变滚动位置）
    CGPoint savedContentOffset = self.tableView.contentOffset;
    
    // 设置 contentOffset 为 (0, 0)，从顶部开始截图
    self.tableView.contentOffset = CGPointZero;
    
    // 将 tableView 渲染到图形上下文中
    [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    // 获取图像
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 结束图形上下文
    UIGraphicsEndImageContext();
    
    // 恢复原来的 contentOffset（恢复滚动位置）
    self.tableView.contentOffset = savedContentOffset;
    
    // 保存图片到相册
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
//    [self saveImageToPhotos:image];
}

- (void)saveImageToPhotos:(UIImage*)savedImage {
    
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    NSString *msg = nil;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    
    [self presentViewController:alert animated:YES completion:nil];
}




@end
